<template>
  <div>
    <upload_item v-if="!encodedImg" @before-upload="decodeUpload" :file="encodedImg" step="step 1" name="请上传隐写图"
                 :format="format1"></upload_item>

    <div v-if="has_file">
      <ul class="onlineuploader-items-list">
        <li class="onlineuploader-item" v-if="encodedImg">
          <Row>
            <Col span="1">
              <div class="onlineuploader-item-image ">
                <div class="image1">
                </div>
              </div>
            </Col>
            <Col span="6" class="column-title">
              <div>{{ file1.name }}</div>
              <span>{{ file1.size }}</span>
            </Col>
            <Col span="3" class="center">
              {{ file1.type }}
            </Col>
            <Col span="1" :offset="13" @click="closeimg">
              <div class="wrong"></div>
            </Col>
          </Row>
        </li>
      </ul>
    </div>

    <Tabs v-model="choose" class="tab" type="card">
      <TabPane label="缩放攻击" name="1">
        <div>请选择缩放比例</div>
        <Slider v-model="value" show-input :min="0.9" :max="1.1" :step="0.01" :marks="marks"></Slider>
      </TabPane>
      <TabPane label="格式转换" name="2">
        <RadioGroup v-model="format">
          <Radio label="png" border></Radio>
          <Radio label="bmp" border></Radio>
<!--          <Radio label="ppm" border></Radio>-->
        </RadioGroup>
      </TabPane>

      <TabPane label="图片压缩" name="3">
        <div>请选择缩放比例</div>
        <Slider v-model="quality" show-input :min="70" :max="100" :step="1" :marks="marks1"></Slider>
      </TabPane>
    </Tabs>


    <Space direction="vertical" type="flex">
      <Button type="success" long @click="upload">开始攻击</Button>
    </Space>

    <Modal v-model="modal1" draggable scrollable :title="title" ok-text="下载图片" @on-ok="download">
      <DescriptionList :col="1" layout="vertical" class="des">
        <Description term="原图(左) 攻击后(右): ">
          <Row class="ivu-text-center" :gutter="24">
            <Col flex="1">
              <img class="up" :src="originImageLink"/>
              <Paragraph class="ivu-mt">原图</Paragraph>
            </Col>
            <Col flex="1">
              <img class="up" :src="returnedImgLink"/>
              <Paragraph class="ivu-mt">攻击后</Paragraph>
            </Col>
          </Row>
        </Description>
      </DescriptionList>
      <!--      <DescriptionList :col="1" layout="vertical">-->
      <!--        <Description term="解密信息为： " >-->
      <!--          <div class="text" v-html="decodeContent"></div>-->
      <!--        </Description>-->
      <!--      </DescriptionList>-->
    </Modal>

  </div>
</template>
<script>

import {resize, convert, compress} from "@/api/encoder_decoder";
import Upload_item from "@/components/upload_item";
import {decoder} from "@/api/encoder_decoder";
import {Description, DescriptionList} from "view-ui-plus";

export default {
  name: "attack",
  components: {Description, DescriptionList, Upload_item},
  data() {
    return {
      title: "",
      modal1: false,
      choose: "1",
      file1: {},
      has_file: false,
      format: 'png',
      value: 1,
      quality: 100,
      marks1: {
        70: '70%',
        80: '80%',
        90: '90%',
        100: {
          style: {
            color: '#ff0000'
          },
          label: '原图'
        }
      },
      marks: {
        0.95: '95%',
        1.1: '110%',
        0.9: '90%',
        1: {
          style: {
            color: '#ff0000'
          },
          label: '原图'
        }
      },
      format1: ['jpg', 'jpeg', 'png'],
      isCollapsed: false,
      BASE_URL: "http://101.34.204.110:5000/static/",
      loadingStatus: false,
      encodedImg: null,
      returnedImgLink: '',
      originImageLink: "",
      // returnedImgLink: 'http://101.34.204.110:5000/static/img_resize_ratiob6NaD.jpg',
      // originImageLink: "http://101.34.204.110:5000/static/img_resize_ratiob6NaD.jpg",
      decodeLoadingStatus: false,
      returntxt: 'sa',
    };
  },
  computed: {
    decodeContent() {
      //this.commend.content是后端传回来的文本数据，就是要对这个数据进行处理
      let arr = this.returntxt.split("");
      return arr.map((item) => {
        return item === "\n" ? "<br>" : item
      }).join("")
    }
  },
  methods: {
    closeimg() {
      this.encodedImg = null
    },

    handleFormatError(file, desc) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: 'File format of ' + file.name + ' is incorrect, please select ' + desc
      });
    },

    handleMaxSize(file, desc) {
      this.$Notice.warning({
        title: '文件大小超出范围',
        desc: 'File  ' + file.name + ' is too large, no more than ' + desc
      });
    },
    upload() {

      if (!this.encodedImg) {
        this.$Notice.error({
          title: "请上传图片",
          desc: "加密需要图片和加密信息才能加密 ",
        });
        return;
      }

      const fileReader = new FileReader();
      fileReader.readAsDataURL(this.encodedImg);
      fileReader.onload = (event) => {
        this.originImageLink = event.target.result;
      };
      if (this.choose === "1") {
        this.decodeLoadingStatus = true;
        this.$Spin.show();
        const that = this;
        resize(this.encodedImg, this.value)
            .then((result) => {
              that.title = "缩放" + that.value + " 攻击"
              console.log(result)
              that.modal1 = true
              // that.returntxt = result.text
              // that.originImageLink = that.encodedImg

              // that.encodedImg = null;
              that.returnedImgLink = that.BASE_URL + result.img_path;
              console.log(that.returnedImgLink)
              that.$Spin.hide();
              that.decodeLoadingStatus = false;
            })
            .catch((error) => {

              that.$Spin.hide();
              that.decodeLoadingStatus = false;
              that.$Notice.error({
                title: "错误",
                desc: error,
              });
            });
      }
      if (this.choose === "2") {
        this.decodeLoadingStatus = true;
        this.$Spin.show();
        const that = this;
        convert(this.encodedImg, this.format)
            .then((result) => {
              that.title = "格式转换 -> " + that.format
              console.log(result)
              that.modal1 = true
              // that.originImageLink = that.encodedImg
              // that.returntxt = result.text
              // that.encodedImg = null;
              that.returnedImgLink = that.BASE_URL + result.img_path;
              console.log(that.returnedImgLink)
              that.$Spin.hide();
              that.decodeLoadingStatus = false;
            })
            .catch((error) => {
              that.$Spin.hide();
              that.decodeLoadingStatus = false;
              that.$Notice.error({
                title: "错误",
                desc: error,
              });
            });
      }

      if (this.choose === "3") {
        this.decodeLoadingStatus = true;
        this.$Spin.show();
        const that = this;
        compress(this.encodedImg, this.quality)
            .then((result) => {
              that.title = "图片压缩 -> " + that.format
              console.log(result)
              that.modal1 = true
              // that.originImageLink = that.encodedImg
              // that.returntxt = result.text
              // that.encodedImg = null;
              that.returnedImgLink = that.BASE_URL + result.img_path;
              console.log(that.returnedImgLink)
              that.$Spin.hide();
              that.decodeLoadingStatus = false;
            })
            .catch((error) => {
              that.$Spin.hide();
              that.decodeLoadingStatus = false;
              that.$Notice.error({
                title: "错误",
                desc: error,
              });
            });
      }
    },

    decodeUpload(file) {
      /**
       * 解码器上传
       */

      // 验证
      if (!/\.(jpg|jpeg|png)$/.test(file.name)) {
        this.handleFormatError(file, "jpg,png")
        return false;
      }
      if (file.size > 1024 * 200) {
        this.handleMaxSize(file, "200kb")
        return false;
      }
      this.encodedImg = file
      this.file1 = {
        size: (file.size / 1024).toFixed(2) + "kb",
        name: file.name,
        type: file.type
      }
      this.has_file = true

      return false;
    },

    getUrlname(url) { //假如传进来的url是 http://www.qq.com/index.html?name=joey 这里一共是有3个斜杠,如果我们想获取index.html
      url = url.split('?')[0];// 我们只要?号前的
      var urlSlashCount = url.split('/').length; // 统计有3斜杠
      return url.split('/')[urlSlashCount - 1].toLowerCase(); //获取数组最后一个
    },

    download() {
      // console.log("下载")
      var image = new Image();
      const name = this.getUrlname(this.returnedImgLink)
      image.setAttribute('crossOrigin', 'anonymous');
      image.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/jpeg"); //得到图片的base64编码数据
        var a = document.createElement("a"); // 生成一个a元素
        var event = new MouseEvent("click"); // 创建一个单击事件
        a.download = name || "photo"; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      }

      image.src = this.returnedImgLink;
    }

  }
}
</script>

<style scoped>
.tab {
  min-height: 200px;
  height: 100%;
  width: 100%;
  padding: 20px;
}

.wrong {
  background-image: url("../assets/wrong.svg");
  background-repeat: no-repeat;
  background-size: 50% 50%;
  /*background-color: red;*/
  width: 100%;
  height: 100%;
  /*background: #259229;*/
  background-position: center;
}

.up {
  height: 100%;
  width: 100%;
}

.des {
  margin-bottom: 20px;
}

.onlineuploader-items-list {
  display: block;
  margin: 0px;
  padding: 0;
  list-style: none;
  /*border: 1px solid #ebeef1;*/
  cursor: pointer;
  box-shadow: 0 1px 2px 0 rgb(60 64 67 / 30%), 0 1px 3px 1px rgb(60 64 67 / 15%);
  border-radius: .625rem;
  border: 1px solid transparent;
  transition: box-shadow .4s, transform .4s;
}

.onlineuploader-items-list:hover {
  border: 1px solid #2b932f;
  transform: translateY(-2%);
}

.onlineuploader-item {
  position: relative;
  margin: 0;
  padding: 5px 16px 5px 22px;
  border-bottom: 1px solid #ebeef1;
  /*border-top: 1px solid #ebeef1;*/
}

.column-title {
  padding-left: 16px;
  padding-right: 16px;
  color: #555;
  overflow: hidden;
}

.column-title div {
  width: 100%;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  font-weight: 400;
  text-shadow: 0 1px 0 rgb(0 0 0 / 15%) !important;
}

.column-title span {
  font-size: 12px;
  color: #979fb8;
  opacity: 0.7;
  font-weight: 300;
}

.onlineuploader-item-image {
  display: flex;
  height: 100%;
  width: 100%;

}

.onlineuploader-item-image div {
  /*position: absolute;*/
  /*top: 0;*/
  /*left: 0;*/
  width: 32px;
  height: 32px;
  /*flex: 1;*/
  margin: auto;
  border-radius: 3px;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center;
  /*box-shadow: 0 2px 5px 0 rgb(147 147 147 / 64%);*/
}

.image1 {
  background-image: url("../assets/JPG_1.svg");
}

.text {
  overflow: auto;
  max-height: 150px;
}

</style>